package biz.yfsoft.app.fastframework.kit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Properties;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509TrustManager;

public class HttpsPost {

	private static String CLIENT_KEYSTORE_PATH = "F:\\Workspace\\FastFramework\\fastframework\\src\\main\\resources\\hy.pfx";
	
	private static String CERT_PASSWORD = "changeit";
	
	private static String SERVER_DOMAIN = "corporbank3.dccnet.com.cn";
	
	private static int TIMEOUT = 30000;

	public static void setCert(String cert,String pass,String domain) {
		CLIENT_KEYSTORE_PATH = cert;
		CERT_PASSWORD = pass;
		SERVER_DOMAIN = domain;
	}

	public static String ssl(String uri, String args) throws Exception {
		HttpsURLConnection con = (HttpsURLConnection) new URL(uri).openConnection();
		
		//创建ssl链接
		javax.net.ssl.SSLSocketFactory factory = null;
		SSLContext ctx = SSLContext.getInstance("TLS");
		char passphrase[] = CERT_PASSWORD.toCharArray();
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); 
//		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		//加载证书文件
		KeyStore ks = KeyStore.getInstance("PKCS12");
		if (!(new File(CLIENT_KEYSTORE_PATH)).isFile()) {
			throw new IOException("Missing keystore = " + CLIENT_KEYSTORE_PATH);
		}
		FileInputStream fis = new FileInputStream(CLIENT_KEYSTORE_PATH);
		ks.load(fis, passphrase);
		kmf.init(ks, passphrase);
		
//		tmf.init(ks);
		ctx.init(kmf.getKeyManagers(),  new MyTrustManager[] { new MyTrustManager() }, new java.security.SecureRandom());
		factory = ctx.getSocketFactory();
		//创建sslsocket
		SSLSocket socket = (SSLSocket) factory.createSocket(SERVER_DOMAIN, 443);
		socket.setSoTimeout(TIMEOUT);
		//建立链接
		socket.startHandshake();
		
		con.setSSLSocketFactory(factory);
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
//		con.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
		con.setRequestMethod("POST");
		con.setDoInput(true);
		con.setDoOutput(true);
		
		System.out.println("ARGS:"+args);
		//传入参数
		OutputStream os = con.getOutputStream();
		os.write(args.getBytes("GBK"));
		os.close();
		con.connect();
		//发起请求
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		//获取返回值
		if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
			br = new BufferedReader(new InputStreamReader(con.getInputStream()));
		}else{
			br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
		}
		//存放到变量中存储
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		con.disconnect();
		//将响应的返回值return
		return sb.toString();
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException { 
        Properties p = System.getProperties(); 
        System.setProperty("file.encoding", "GBK");
        for (Map.Entry<Object, Object> entry : p.entrySet()) { 
                System.out.println(entry.getKey() + " = " + entry.getValue()); 
        }
        String str = "%3C%3Fxml++version%3D%221.0%22+encoding%3D%22GB2312%22+standalone%3D%22no%22+%3F%3E%0A%3Cicbc_corporbank_credit_pay%3E%0A%3CinterfaceName%3EICBC_CORPORBANK_CREDIT_MODIFY%3C%2FinterfaceName%3E%0A%3CinterfaceVersion%3E1.0.0.2%3C%2FinterfaceVersion%3E%0A%3Corder%3E%0A%3CorderID%3EO1440572383667%3C%2ForderID%3E%0A%3Camount%3E%3C%2Famount%3E%0A%3CcurrType%3E%3C%2FcurrType%3E%0A%3CfeeAmt%3E%3C%2FfeeAmt%3E%0A%3CmerOrderTime%3E20150826145943%3C%2FmerOrderTime%3E%0A%3CorderExpire%3E%3C%2ForderExpire%3E%0A%3CorderState%3E%3C%2ForderState%3E%0A%3CBankNotifyTime%3E20150827164709%3C%2FBankNotifyTime%3E%0A%3C%2Forder%3E%0A%3Crefund%3E%0A%3CrefundFlag%3E%3C%2FrefundFlag%3E%0A%3CrefundAmtSum%3E%3C%2FrefundAmtSum%3E%0A%3CappRefundAmt%3E%3C%2FappRefundAmt%3E%0A%3C%2Frefund%3E%0A%3Cseller%3E%0A%3CsellerAcct%3E%3C%2FsellerAcct%3E%0A%3CsellerName%3E%3C%2FsellerName%3E%0A%3C%2Fseller%3E%0A%3Cmerchant%3E%0A%3CmerID%3E1103EC13761206%3C%2FmerID%3E%0A%3CmerAcctNum%3E%3C%2FmerAcctNum%3E%0A%3CmerAcctName%3E%3C%2FmerAcctName%3E%0A%3C%2Fmerchant%3E%0A%3Ctran%3E%3CrequestType%3E4%3C%2FrequestType%3E%0A%3CrequestResult%3E1%3C%2FrequestResult%3E%0A%3CErrMsg%3E%0A%5B40977%5D%C9%CC%BB%A7%D6%A4%CA%E9%D0%C5%CF%A2%B4%ED%3C%2FErrMsg%3E%0A%3C%2Ftran%3E%0A%3Cnotify%3E%0A%3CbuyerPhoneNum%3E%3C%2FbuyerPhoneNum%3E%0A%3CsellerPhoneNum%3E%3C%2FsellerPhoneNum%3E%0A%3CmerURL%3E%3C%2FmerURL%3E%0A%3C%2Fnotify%3E%0A%3Csecurity%3E%0A%3CbankSignMsg%3EVnKzfKrbrDCeqkGG8jzum51u8My8zL5QGvi%2BH0coFHsupdqGPkNWSQRuq9t1hRCnOYhPTfyRlRpjWZVGkQmLjlqohQ5fntla3FKeZCmRa0FGrp9G%2F2BoVgSPlUBWNJXSdg5e0t7iblL4hshf3tPwbcbsa9XVxvS5Qn1hQspd%2BZc%3D%3C%2FbankSignMsg%3E%0A%3C%2Fsecurity%3E%0A%3C%2Ficbc_corporbank_credit_pay%3E%0A";
        str = URLDecoder.decode(str, "gbk");
        System.out.println(str);
	}

}

class MyTrustManager implements X509TrustManager {
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		;
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		;
	}

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}
